package com.sxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxy.controller.common.R;
import com.sxy.dto.DishDto;
import com.sxy.pojo.Category;
import com.sxy.pojo.Dish;
import com.sxy.pojo.DishFlavor;
import com.sxy.service.CategoryService;
import com.sxy.service.DishFlavorService;
import com.sxy.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清除Redis中对应分类缓存
        String keys = "dish" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);
        return R.success("新增菜品成功~");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> getByPage(int page, int pageSize, String name) {
        log.info("getById...");
        //构造分页构造器对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件查询器
        LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();
        //添加条件
        dqw.like(name != null, Dish::getName, name);
        dqw.orderByDesc(Dish::getUpdateTime);

        //调用业务层方法
        dishService.page(dishPage, dqw);

        //对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage);

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        log.info("根据id查询菜品");
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        if (dishDto == null) {
            return R.error("没有查到该菜品");
        }
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @Transactional
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish*");
//        redisTemplate.delete(keys);
        //清理分类下的菜品缓存
        String keys = "dish" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);
        return R.success("修改菜品成功~");
    }

    /**
     * 删除一条或多条数据
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids) {
        log.info("根据id删除菜品...");
        dishService.removeWithFlavor(ids);
        return R.success("删除成功~");
    }

    /**
     * 更改菜品状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, Long[] ids) {
        log.info("启用或停用菜品...");
        Dish dish;
        for (Long id : ids) {
            dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("操作菜品成功~");
    }

    @GetMapping("/list")
    public R<List<DishDto>> getByCategoryId(Dish dish) {
        log.info("getByCategoryId..");
        List<DishDto> dishDtoList = null;
        //动态构造Redis中菜品的 key
        String key = "dish" + dish.getCategoryId() + "_" + dish.getStatus();

        //从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果数据存在，直接返回，不需要查询数据库
            return R.success(dishDtoList);
        }

        //如果数据不存在，则查询数据库，将查询到的菜品数据缓存到redis中
        //创建条件查询
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        //添加状态条件,查询起售的菜品
        lqw.eq(Dish::getStatus, 1);

        //添加排序条件
        lqw.orderByAsc(Dish::getUpdateTime);

        //执行查询
        List<Dish> list = dishService.list(lqw);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝对象
            BeanUtils.copyProperties(item, dishDto);
            //获取每个对象的分类id
            Long categoryId = item.getCategoryId();

            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            //保存分类名称
            if (category != null) {
                String name = category.getName();
                dishDto.setCategoryName(name);
            }
            //查询口味数据,获取当前菜品id
            Long dishId = item.getId();
            //根据菜品id查询菜品口味
            LambdaQueryWrapper<DishFlavor> lqw1 = new LambdaQueryWrapper<>();
            //添加条件
            lqw1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw1);

            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        //将查询到的数据存到Redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);

    }
    /*@GetMapping("/list")
    public R<List<Dish>> getByCategoryId(Dish dish) {
        log.info("getByCategoryId..");
        //创建条件查询
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.eq(Dish::getCategoryId, dish.getCategoryId());
        //添加状态条件,查询起售的菜品
        lqw.eq(Dish::getStatus, 1);

        //添加排序条件
        lqw.orderByAsc(Dish::getUpdateTime);

        //执行查询
        List<Dish> list = dishService.list(lqw);

        return R.success(list);

    }*/

}
